package com.rkc.mq;

import com.rabbitmq.client.Channel;
import com.rkc.model.CouponRecordMessage;
import com.rkc.service.CouponRecordService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @author `RKC`
 * @date 2021/11/6 16:18
 */
@Slf4j
@Component
@RabbitListener(queues = "${mqconfig.coupon_release_queue}")
public class CouponRecordMQListener {

    @Autowired
    private CouponRecordService couponRecordService;

    @RabbitHandler
    public void releaseCouponRecord(CouponRecordMessage couponRecordMessage, Message message, Channel channel) throws IOException {
        log.info("监听到消息：releaseCouponRecord消息内容：{}", couponRecordMessage);
        long msgTag = message.getMessageProperties().getDeliveryTag();
        try {
            //数据库更新成功，需要对该消息进行确认消息消费成功
            if (couponRecordService.releaseCouponRecord(couponRecordMessage)) {
                channel.basicAck(msgTag, false);
            } else {
                log.error("释放优惠券失败，flag=false：{}", couponRecordMessage);
                channel.basicReject(msgTag, true);
            }
        } catch (IOException e) {
            log.error("释放优惠券异常：{}，msg：{}", e, couponRecordMessage);
            channel.basicReject(msgTag, true);
        }
    }
}
